/**
 * fantasy
 */
package com.fantasy.easy.sys.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.fantasy.easy.core.Const;
import com.fantasy.easy.core.SessionSubjectUtils;

/**
 * @author fantasy 2020年11月18日 用户语言切换过滤器
 */
@Component
@Order(1) // 过滤器加载的顺序 默认Integer.MAXVALUE
@WebFilter(urlPatterns = "/*", filterName = "easyLocaleFilter") // 拦截所有路径
public class EasyLocaleFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		try {
			String lang = req.getParameter("lang");
			if(lang == null) {
				HttpSession session = req.getSession(false);
				if(session != null) {
					Object langTmp = session.getAttribute(lang);
					if(langTmp != null) {
						lang = (String)langTmp;
					}
				}
			}
			if (lang == null) {
				Cookie[] cookies = req.getCookies();
				if(cookies != null && cookies.length > 0){
				     for (Cookie cookie : cookies){
				         if(StringUtils.equals("lang", cookie.getName())) {
				        	 lang = cookie.getValue();
				         }
				     }
				 }
			}
			if (StringUtils.equals(Const.LANG_CN, lang)) {
				SessionSubjectUtils.setLocale(Locale.SIMPLIFIED_CHINESE);
			}
			if (lang != null && StringUtils.equals(Const.LANG_EN, lang)) {
				SessionSubjectUtils.setLocale(Locale.US);
			}
		} finally {
			chain.doFilter(request, response);
		}
	}

}